package com.czy.seed.mvc.home.controller;

import com.czy.seed.mvc.home.entity.AddressManager;
import com.czy.seed.mvc.home.entity.Merchant;
import com.czy.seed.mvc.home.entity.QuoteOrCompare;
import com.czy.seed.mvc.home.service.AddressManagerService;
import com.czy.seed.mvc.home.service.MerchantService;
import com.czy.seed.mvc.home.service.QuotationService;
import com.czy.seed.mvc.home.service.QuoteOrCompareService;
import com.czy.seed.mvc.util.FilesUpload;
import com.czy.seed.mvc.util.PrincipalUtil;
import com.czy.seed.mvc.util.Res;
import com.czy.seed.mybatis.base.QueryParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/home/quote_or_compare")
public class QuoteOrCompareController {

    @Autowired
    private QuoteOrCompareService quoteOrCompareService;

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private QuotationService quotationService;

    @Autowired
    AddressManagerService addressManagerService;
    public static Logger logger = LoggerFactory.getLogger(QuoteOrCompareController.class);

    /**
     * 查询信息竞价、询价单信息
     *
     * @return
     */
    @RequestMapping("/selectAll")
    public Res selectAll() {
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        QueryParams queryParams = new QueryParams(QuoteOrCompare.class);
       /* 根据Id倒序排序，取最新的在前面*/
        queryParams.orderBy("id").desc();
        try {
            List<QuoteOrCompare> quoteOrCompareList = quoteOrCompareService.selectAll(1L);
            pageInfo.put("quoteOrCompare", quoteOrCompareList);
        } catch (Exception e) {
            logger.error("查询全部竞价、询价单信息失败：{}", e);
        }
        return Res.ok(pageInfo);
    }

    /**
     * 查询信息竞价、询价单信息跟自己有关的
     *
     * @return
     */
    @RequestMapping("/selectAllByUserId")
    public Res selectAllByUserId() {
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try {
            QueryParams query = new QueryParams(Merchant.class);
            QueryParams.Criteria crit = query.createCriteria();
            crit.andEqualTo("userId", PrincipalUtil.getLoginUser().getId());
            List<Merchant> merchants = merchantService.selectListByParams(query);
            List<QuoteOrCompare> quoteOrCompareList =null;
            QueryParams queryParams = new QueryParams(QuoteOrCompare.class);
            QueryParams.Criteria criteria = queryParams.createCriteria();
            if(merchants.size()>0) {
                criteria.andCondition("QUOTATIONLIST.MERCHANT_ID = " + merchants.get(0).getId());
                criteria.andEqualTo("type", 0L);
                quoteOrCompareList = quoteOrCompareService.selectListRelativeByParams(queryParams);
            }
            pageInfo.put("quoteOrCompare", quoteOrCompareList);
        } catch (Exception e) {
            logger.error("查询跟自己有关的竞价、询价单信息失败：{}", e);
        }
        return Res.ok(pageInfo);
    }

    /**
     * 查询信息竞价、询价单信息跟自己有关的
     *
     * @return
     */
    @RequestMapping("/selectAllByUserId_")
    public Res selectAllByUserId_() {
        Map<String, Object> pageInfo = new HashMap<String, Object>();
        try {
            QueryParams queryParams = new QueryParams(QuoteOrCompare.class);
            QueryParams.Criteria criteria = queryParams.createCriteria();
            criteria.andCondition("quote_or_compare.INITIATOR_ID = " + PrincipalUtil.getLoginUser().getId());
            criteria.andEqualTo("type", 0L);
            List<QuoteOrCompare> quoteOrCompareList = quoteOrCompareService.selectListRelativeByParams(queryParams);
            pageInfo.put("quoteOrCompare", quoteOrCompareList);
        } catch (Exception e) {
            logger.error("查询信息竞价、询价单信息失败：{}", e);
        }
        return Res.ok(pageInfo);
    }
/**
 * 根据采购清单查询询价单
 * */
    @RequestMapping("/selectByUserId_")
    public Res selectByUserId_(long id) {
        Map<String, Object> pageInfo = new HashMap<String, Object>();
        try {
            QueryParams queryParams = new QueryParams(QuoteOrCompare.class);
            QueryParams.Criteria criteria = queryParams.createCriteria();
            criteria.andEqualTo("purchaseId",id);
            criteria.andEqualTo("type", 0L);
            QueryParams queryParam = new QueryParams(AddressManager.class);
            QueryParams.Criteria criterias = queryParam.createCriteria();
            criterias.andEqualTo("userId",PrincipalUtil.getLoginUser().getId());
            criterias.andEqualTo("ischeck",1);
            List<AddressManager> addressManagers = addressManagerService.selectListByParams(queryParam);
            pageInfo.put("addressManagers",addressManagers);
            List<QuoteOrCompare> quoteOrCompareList = quoteOrCompareService.selectListRelativeByParams(queryParams);
            if(quoteOrCompareList.size()>0) {
                pageInfo.put("size", "1");
            }else{
                pageInfo.put("size", "0");
            }
            pageInfo.put("quoteOrCompare", quoteOrCompareList);
        } catch (Exception e) {
            logger.error("查询信息竞价、询价单信息失败：{}", e);
        }
        return Res.ok(pageInfo);
    }
    //根据采购清单更新询价单及其报价单状态
    @RequestMapping("/uodateTypeAll")
    public Res uodateTypeAll(long id){
        Map<String, Object> pageInfo = new HashMap<String, Object>();
        pageInfo= quoteOrCompareService.uodateTypeAll(id);
        return Res.ok(pageInfo);
    }


    /**
     * 添加竞价，询价单
     *
     * @param request
     * @return
     */

    @RequestMapping("/addQuoteOrCompare")
    public Res addQuoteOrCompare(HttpServletRequest request) {

        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try {
            pageInfo = quoteOrCompareService.addQuoteOrCompare_impl(request);
        } catch (Exception e) {
            pageInfo.put("message", e.getMessage());
            logger.error("添加竞价，询价单失败：{}", e);
        }
        return Res.ok(pageInfo);
    }

    /**
     * 添加竞价信息和所关联的询价信息
     */

    @RequestMapping("/addQuoteAndCompare")
    public Res addQuoteAndCompare(HttpServletRequest request) {

        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try {
            pageInfo = quoteOrCompareService.addQuoteAndCompare_impl(request);
        } catch (Exception e) {
            pageInfo.put("message", e.getMessage());
            logger.error("添加竞价信息和所关联的询价信息失败：{}", e);
        }
        return Res.ok(pageInfo);

    }

    /**
     * 上传文件信息
     *
     * @param multiReq
     * @return
     */
    @RequestMapping("/uploadFile")
    public Res uploadFile(MultipartHttpServletRequest multiReq) {

        String url = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        try {
            new FilesUpload().Upload("file", url, multiReq, null);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            logger.error("上传文件信息失败：{}", e);
            e.printStackTrace();
        }
        return Res.ok();

    }
}
